package com.md24housecall.activity;

import java.io.File;

import android.app.Application;
import android.content.SharedPreferences;
import android.util.Log;

import com.md24housecall.util.GlobalConstant;
import com.md24housecall.util.MyLog;
import com.md24housecall.util.Utils;

public class TeleMedicineApplication extends Application {
	private Utils util = Utils.getInstance();
	private GlobalConstant constant = GlobalConstant.getInstance();
	private static final String USER_PREFS = "com.google.android.gms.samples.wallet.USER_PREFS";
    private static final String KEY_USERNAME = "com.google.android.gms.samples.wallet.KEY_USERNAME";

    private String mUserName;
    private SharedPreferences mPrefs;

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		mPrefs = getSharedPreferences(USER_PREFS, MODE_PRIVATE);
        mUserName = mPrefs.getString(KEY_USERNAME, null);
		Thread.setDefaultUncaughtExceptionHandler(handler);
		if (util.getCheckAppFirstRun(this)) 
		{
			util.saveCheckAppFirstRun(this, false);
			File f = new File(constant.file, "TeleMedicine");
			String deleteCmd = "rm -r " + f.getAbsolutePath();
			Runtime runtime = Runtime.getRuntime();
			try {
				runtime.exec(deleteCmd);
			} catch (Exception e) {
//				e.printStackTrace();
				MyLog.d(GlobalConstant.TAG, "exception delete telemedicine folder: "+e.getMessage());
			}
		}
	}

	public boolean isLoggedIn() {
        return mUserName != null;
    }

    public void login(String userName) {
        mUserName = userName;
        mPrefs.edit().putString(KEY_USERNAME, mUserName).commit();
    }

    public void logout() {
        mUserName = null;
        mPrefs.edit().remove(KEY_USERNAME).commit();
    }

    public String getAccountName() {
        return mPrefs.getString(KEY_USERNAME, null);
    }
    
	@Override
	public void onLowMemory() {
		// TODO Auto-generated method stub
		super.onLowMemory();
//		BitmapAjaxCallback.clearCache();
	}

	private Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() {
		public void uncaughtException(Thread thread, Throwable ex) {
			Log.e(GlobalConstant.TAG, "Uncaught exception is: ", ex);
			try {
				restartApp();
			} catch (Exception e) {
				e.printStackTrace();
			}
			// log it & phone home.
			// androidDefaultUEH.uncaughtException(thread, ex);
		}
	};

	// restart the application if there are some uncaught exception
	private void restartApp() {
//		Intent i = getBaseContext().getPackageManager()
//				.getLaunchIntentForPackage(getBaseContext().getPackageName());
//		PendingIntent intent = PendingIntent.getActivity(this, 0, i,
//				i.getFlags());
//		AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
//		mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 2000, intent);
//		System.exit(2);
		android.os.Process.killProcess(android.os.Process.myPid());
	}
}
